Hard
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
1 | Input: [3,3,5,0,0,3,1,4] |
Example 2:
1 | Input: [1,2,3,4,5] |
Example 3:
1 | Input: [7,6,4,3,1] |
- 改良版brute force。一维dp list 用来存储一次交易的最大利润。first_idx list存储第一次交易结束时间点,first_max存储第一次交易,ans存两次交易最大值。每次遍历搜索每次潜在的第一次交易结束时间,进行比较,存储结果。
1 | class Solution: |
2.使用局部和全局两个dp list
最近在刷动态规划的题,这篇文章是我写的动态规划一点想法,和大家分享一下
以及这题的参考
1 | class Solution { |
Syntax:
- 最大值。Math.max。大写
- new的用法